package com.zlyx.easy.core.utils;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 线程操作工具类
 * </p>
 *
 * @author 赵光
 * @since 2019年5月22日
 */
@Component
public class ThreadUtils {

	private static ExecutorService threadPool;
	private static int THREAD_COUNT = Runtime.getRuntime().availableProcessors() * 2;

	public ThreadUtils(@Autowired(required = false) ExecutorService threadPool) {
		if (threadPool == null) {
			threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
		}
		ThreadUtils.threadPool = threadPool;
	}

	/**
	 * 分配一个线程执行任务
	 * 
	 * @param runnable
	 * @return
	 */
	public static Thread execute(Runnable runnable) {
		return execute(convert(runnable));
	}

	/**
	 * 分配一个线程执行任务
	 * 
	 * @param thread
	 * @return
	 */
	public static Thread execute(Thread thread) {
		return execute(thread.getName(), thread);
	}

	/**
	 * 分配一个线程执行任务
	 * 
	 * @param thread
	 * @return
	 * @return
	 */
	public static Thread execute(String threadName, Runnable runnable) {
		return execute(threadName, convert(runnable));
	}

	/**
	 * 分配一个线程执行任务
	 * 
	 * @param name
	 * @param command
	 * @return
	 */
	public static Thread execute(String threadName, Thread thread) {
		thread.setName(threadName);
		threadPool().execute(thread);
		return thread;
	}

	/**
	 * 停止线程池
	 * 
	 * @return
	 * 
	 * @return
	 */
	public static List<Runnable> shutdownNow() {
		return threadPool().shutdownNow();
	}

	/**
	 * 停止线程池
	 * 
	 * @return
	 */
	public static void shutdown() {
		threadPool().shutdown();
	}

	/**
	 * 获取线程池
	 * 
	 * @return
	 */
	public static ExecutorService threadPool() {
		if (threadPool == null) {
			threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
		}
		return threadPool;
	}

	/**
	 * 获取当前抛异常类名
	 * 
	 * @return
	 */
	public static String getCurrentClassName() {
		return Thread.currentThread().getStackTrace()[3].getClassName();
	}

	/**
	 * 将Runnable接口转换为Thread
	 * 
	 * @param runnable
	 * @return
	 */
	public static Thread convert(Runnable runnable) {
		return new Thread(runnable);
	}

	/**
	 * 休眠当前线程
	 * 
	 * @param millis
	 */
	@SuppressWarnings("static-access")
	public static void sleep(int millis) {
		try {
			Thread.currentThread().sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 线程哈希码
	 * 
	 * @return
	 */
	public static int getCode() {
		return Thread.currentThread().hashCode();
	}

	/**
	 * 线程名
	 * 
	 * @return
	 */
	public static String getName() {
		return Thread.currentThread().getName();
	}
}
